import java.util.Comparator;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lenovo
 * Date: 2022-08-31
 * Time: 14:11
 */
class Student implements Comparable<Student>/*实现comparable接口*/{
    public int age;
    public String name;

    public Student(int age, String name)  {
        this.age = age;
        this.name = name;
    }

    @Override//引用类型的比较从写了equals方法
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age ;//&& Objects.equals(name, student.name);//这里的equals方法为Object里带两个参数的静态方法,这这个方法下面又会调用被String重写的equals方法
    }

    @Override
    public int hashCode() {
        return Objects.hash(age, name);
    }

    @Override//实现comparable接口,重写compareTo方法
    public int compareTo(Student o) {
        return this.age-o.age;
    }
}
//创建一个类,来实现比较器
//比较name
class NameComparator implements Comparator<Student> {

    @Override
    public int compare(Student o1, Student o2) {
        return o1.name.compareTo(o2.name);//String类型比较大小
    }
}
//比较age
class AgeComparator implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
        return o1.age-o2.age;
    }
}
public class Test {
    public static void main(String[] args) {
     Student student1 = new Student(10,"abc");
     Student student2 = new Student(10,"ab");
     Student student3 = new Student(15,"dgh");
        System.out.println(student1==student2);//比较的两个引用是否为同一个引用
        System.out.println(student1.equals(student2));// true 重写的equals方法里自定义年龄相等,两个引用就相等的逻辑
        System.out.println(student1.compareTo(student2));//0
        System.out.println(student1.compareTo(student3));//-5
        System.out.println("=============");
        //比较器
        NameComparator nameComparator = new NameComparator();
        System.out.println(nameComparator.compare(student1, student2));//比较Sting类型
        AgeComparator ageComparator = new AgeComparator();
        System.out.println(ageComparator.compare(student1, student3));//-5

    }
}
